package com.dmall.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dmall.entity.Product;
import com.dmall.service.ProductService;

/**
 *  商品列表-控制层
 * @author ccp 蔡陈鹏
 *
 */
@WebServlet("/productshoplist.do")
public class ProductShopListServelet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	ProductService ps = new ProductService();

	public ProductShopListServelet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置请求编码的格式
		request.setCharacterEncoding("utf-8");

		String op = "";
		System.out.println(op);
		// 判断防止空指针
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		if ("query".equals(op)) {
			// 查询
			doQuery(request, response);
		} else {
			// 查询
			doQuery(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	/**
	 * 分页查询
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doQuery(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 接收表单提交的数据，获胜name="keywords"的值
		String keywords = "";
		if (request.getParameter("keywords") != null) {
			keywords = request.getParameter("keywords");
		}

		System.out.println("keywords :" + keywords);

		// keywords-传递的查询的关键字
		List<Product> list = ps.getProduct(keywords);

		// 可以存放在request session中
		request.setAttribute("keywords", keywords);

		// 将list集合对象存在request请求范围内，其中双引号list（key）
		request.setAttribute("list", list);
		list.forEach(System.out::println);
		
		// 从servlet跳转到jsp页面
		request.getRequestDispatcher("./front/productshoplist.jsp").forward(request, response);

	}
}
